package com.xy.lang.util;

import com.xy.lang.domain.tuples.Pair;

import java.util.Iterator;
import java.util.Objects;

public class StringIterator implements Iterator<String> {

    private String splitter = ",";
    private String value;
    private int currentIndex;

    public StringIterator(String value) {
        Objects.requireNonNull(value);
        this.value = value;
        this.currentIndex = 0;
    }

    public StringIterator(String value, String splitter) {
        this(value);
        Objects.requireNonNull(splitter);
        this.splitter = splitter;
    }

    @Override
    public boolean hasNext() {
        return currentIndex > -1;
    }

    @Override
    public String next() {
        if(currentIndex < 0) {
            return null;
        }
        Pair<Integer, String> pair = next0();
        if(pair.getValue1() > -1) {
            currentIndex = pair.getValue1() + splitter.length();
        } else {
            currentIndex = -1;
        }
        return pair.getValue2();
    }

    private Pair<Integer, String> next0() {
        int endIndex = value.indexOf(splitter, currentIndex);
        if(endIndex < 0) {
            return new Pair<>(endIndex, value.substring(currentIndex));
        }
        return new Pair<>(endIndex, value.substring(currentIndex, endIndex));
    }

    public void reset() {
        currentIndex = 0;
    }


    /// tests

    public static void main(String[] args) {
        StringIterator iterator = null;
        System.out.println();

        iterator = new StringIterator("");
        print(iterator);

        iterator = new StringIterator("  ");
        print(iterator);

        iterator = new StringIterator("1");
        print(iterator);

        iterator = new StringIterator("1,");
        print(iterator);

        iterator = new StringIterator("1,2");
        print(iterator);

        iterator = new StringIterator(",2");
        print(iterator);
    }

    static void print(StringIterator iterator) {
        System.out.print("## ");
        for(;iterator.hasNext();) {
            System.out.print(iterator.next());
        }
        System.out.println();
    }


}
